package com.spcloud.service.controller;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.spcloud.service.config.kafka.MessageBinder;
import com.spcloud.service.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author GuoChunbo
 * @create 2020-02-18 14:23
 * @Description: 类的描述
 */
@RestController
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    MessageBinder messageBinder;

    @GetMapping("/info")
    public String info() {
        return "User Info";
    }

    /**
     * 注册
     * @return
     */
    @GetMapping("/reg")
    public String reg(User user){

        user.setId((int)(Math.random() *1000));

        //发送消息  destination,message
        //必须是json类型消息
        messageBinder.regUserSender().send(MessageBuilder.withPayload(JSON.toJSONString(user)).build());
        return  "success";
    }

    /**
     * 使用断路器保护服务之间的调用
     *
     * @return
     */
    @HystrixCommand(fallbackMethod = "showOrderFallBack")
    @GetMapping("/orderInfo")
    public String showOrder() {
        //调用订单服务
        //如果是springcloud 应用 建议使用服务名称 http://service-order/info
        //不是springcloud 应用 用http://localhost:8082/info

        //service-order 对应 8082 , 8092
        String res = restTemplate.getForObject("http://service-order/info", String.class);
        return res;
    }

    /**
     * 服务调用失败的回调方法
     * @return
     */
    public String showOrderFallBack(){
        return "User - Order Info";
    }
}
